package com.california.payopenapi.utils;

import com.alibaba.dubbo.rpc.RpcContext;
import com.california.pay.model.OrderPayNotifyResultReq;
import com.california.pay.model.PersonOrderPayReq;
import com.california.pay.model.PersonOrderPayRsp;
import com.california.payopenapi.entity.PayOrderRequest;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.tomcat.jni.Thread;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description:
 * @author: KeyboardMan
 * @Date: Create in 2018-12-10:0:46
 */
public class BeanUtil {

    private static final ThreadLocal<BeanUtil> LOCAL = new ThreadLocal<BeanUtil>() {
        @Override
        protected BeanUtil initialValue() {
            return new BeanUtil();
        }
    };

    private BeanUtil() {}

    public static BeanUtil getContext() {
        ExecutorService service = Executors.newSingleThreadExecutor();
        return LOCAL.get();
    }

    public Map<String,Object> obj2Map(Object bean) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        Class type = bean.getClass();
        Map returnMap = new HashMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo
                .getPropertyDescriptors();
        int propertyDescriptorsLength = propertyDescriptors.length;
        for (int i = 0; i < propertyDescriptorsLength; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, "");
                }
            }
        }
        return returnMap;
    }

    public PersonOrderPayReq payOrder2PersonOrderPayReq(PayOrderRequest payOrderRequest) {
        PersonOrderPayReq payReq = new PersonOrderPayReq();
        try {
            BeanUtils.copyProperties(payReq,payOrderRequest);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return payReq;
    }
}
